import React from "react";
import {Menu} from "antd";

import BaseComponent from "../../../../redare/components/BaseComponent";
import {getLoginUserInfo, getWorkbenchFunMap} from "../../utils/WorkbenchUtil";

function hasPermission({funId, funIdAll} = {}) {
    let funIds;
    if (funId) {
        if (funId instanceof Array) {
            funIds = funId;
        } else {
            funIds = funId.split(',')
        }
    }
    if (!funIds || funIds.length === 0) {
        return false;
    }
    let _user = getLoginUserInfo();
    if (_user.root) {
        return true;
    }
    let _bool = funIdAll;
    let _funMap = getWorkbenchFunMap();
    for (let i = 0; i < funIds.length; i++) {
        let funId = funIds[i];
        if (funIdAll) {
            if (!_funMap.hasOwnProperty(funId)) {
                _bool = false;
                break;
            }
        } else {
            if (_funMap.hasOwnProperty(funId)) {
                _bool = true;
                break;
            }
        }
    }
    return _bool;
}

export default class FunPermission extends BaseComponent {

    static defaultProps = {
        funId: undefined,//功能ID string或String[]
        funIdAll: false,//是否全部满足功能ID
        noPermissionComponent: undefined//无权限展示的内容
    };

    render() {
        if (hasPermission(this.props)) {
            return (
                <>
                    {
                        this.props.children
                    }
                </>
            );
        }

        return this.props.noPermissionComponent || null
    }
}

class MenuItem extends Menu.Item {

    render() {
        if (hasPermission(this.props)) {
            return super.render();
        }
        return null;
    }
}

FunPermission.MenuItem = MenuItem;
